<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Cart;
use App\Http\Controllers\Api\V1\Requests\CartRequest;
use App\Http\Controllers\Api\V1\Resources\CartResource;

class CartsController extends Controller
{
	public function store(CartRequest $request)
    {
        $cart = $request->user()->addCart();
        return new CartResource($cart);
    }

    public function index()
    {
        $carts = request()->user()->carts()->where('is_closed',false)->get();
        return  CartResource::collection($carts);
    }

     public function count()
    {
        $total = request()->user()->carts()->where('is_closed',false)->sum('number');
        return response()->json(['total' => $total]);
    }

    public function update(Cart $cart)
    {
     $this->authorize('own', $cart);
       if(request('number') > 0){

            $cart->update(['number'=>request('number')]);
       }

        return response(null, 204);
    }

     public function destroy(Cart $cart)
    {
        $this->authorize('own', $cart);
        $cart->delete();
        return response(null, 204);
    }
}
